package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.Discussion;
import com.scuec.trainingmanagementsys.entity.Teacher;
import com.scuec.trainingmanagementsys.service.TeacherService;
import com.scuec.trainingmanagementsys.service.DiscussionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/discussion")
@CrossOrigin
public class DiscussionController {

    @Autowired
    private DiscussionService discussionService;
    @Autowired
    private TeacherService teacherService;

    // 获取所有讨论主题
    @GetMapping("/list")
    public Map<String, Object> getAllDiscussions() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Discussion> discussions = discussionService.getAllDiscussions();

            List<Map<String, Object>> discussionList = discussions.stream()
                    .map(discussion -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("discussionId", discussion.getDiscussionId());
                        map.put("discussionContent", discussion.getDiscussionContent());
                        map.put("createTime", discussion.getCreateTime());
                        map.put("userName", discussion.getUserName());
                        // 新增：返回 teacherId 和 studentId
                        map.put("teacherId", discussion.getTeacherId());
                        map.put("studentId", discussion.getStudentId());

                        String userTypeText = Optional.ofNullable(discussion.getUserType())
                                .map(type -> "teacher".equals(type) ? "教师" : "学生")
                                .orElse("未知");
                        map.put("userTypeText", userTypeText);
                        return map;
                    })
                    .collect(Collectors.toList());

            result.put("code", 200);
            result.put("data", discussionList);
            result.put("message", "success");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取讨论列表失败: " + e.getMessage());
        }
        return result;
    }

    // 获取讨论详情
    @GetMapping("/detail/{discussionId}")
    public Map<String, Object> getDiscussionDetail(@PathVariable Integer discussionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Discussion discussion = discussionService.getDiscussionById(discussionId);

            if (discussion != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("discussionId", discussion.getDiscussionId());
                map.put("discussionContent", discussion.getDiscussionContent());
                map.put("createTime", discussion.getCreateTime());
                map.put("userName", discussion.getUserName()); // 直接使用从数据库查询的用户名

                // 安全地设置userTypeText
                String userTypeText = Optional.ofNullable(discussion.getUserType())
                        .map(type -> "teacher".equals(type) ? "教师" : "学生")
                        .orElse("未知");
                map.put("userTypeText", userTypeText);

                result.put("code", 200);
                result.put("data", map);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "讨论不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取讨论详情失败: " + e.getMessage());
        }
        return result;
    }

    // 删除讨论主题
    @DeleteMapping("/delete/{discussionId}")
    public Map<String, Object> deleteDiscussion(@PathVariable Integer discussionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rows = discussionService.deleteDiscussion(discussionId);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "讨论删除成功");
            } else {
                result.put("success", false);
                result.put("message", "讨论删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "讨论删除失败: " + e.getMessage());
        }
        return result;
    }

    // 添加新方法：根据学生ID查询讨论
    @GetMapping("/student/{studentId}")
    public Map<String, Object> getDiscussionsByStudentId(@PathVariable String studentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Discussion> list = discussionService.findByStudentId(studentId);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", list);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }


    @PostMapping("/add")
    public Map<String, Object> addDiscussion(
            @RequestBody Discussion discussion,
            @RequestParam("studentId") String studentId) { // 添加学生ID参数

        Map<String, Object> result = new HashMap<>();
        try {
            // 设置学生ID
            discussion.setStudentId(Integer.valueOf(studentId));
            // 教师ID设为null（学生发布）
            discussion.setTeacherId(null);

            // 验证字段
            if (discussion.getDiscussionContent() == null || discussion.getDiscussionContent().isEmpty()) {
                result.put("success", false);
                result.put("message", "讨论内容不能为空");
                return result;
            }

            int rows = discussionService.insertDiscussion(discussion);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "讨论发布成功");
            } else {
                result.put("success", false);
                result.put("message", "讨论发布失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "讨论发布失败: " + e.getMessage());
        }
        return result;
    }

    // 根据教师编号查询讨论
    @GetMapping("/teacher/{teacherNumber}")
    public Map<String, Object> getDiscussionsByTeacherNumber(@PathVariable String teacherNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Discussion> list = discussionService.findDiscussionsByTeacherNumber(teacherNumber);
            List<Map<String, Object>> discussionList = list.stream()
                    .map(discussion -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("discussionId", discussion.getDiscussionId());
                        map.put("discussionContent", discussion.getDiscussionContent());
                        map.put("createTime", discussion.getCreateTime());
                        map.put("userName", discussion.getUserName());
                        map.put("userTypeText", "教师");
                        // 新增：返回 teacherId
                        map.put("teacherId", discussion.getTeacherId());
                        return map;
                    })
                    .collect(Collectors.toList());

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", discussionList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/teacher/add")
    public Map<String, Object> addTeacherDiscussion(
            @RequestBody Discussion discussion,
            @RequestParam("teacherNumber") String teacherNumber) {

        Map<String, Object> result = new HashMap<>();
        try {
            discussion.setStudentId(null); // 教师发布，学生ID显式置空
            discussion.setTeacherId(null); // 先置空，后续从教师信息赋值

            // 验证讨论内容非空
            if (discussion.getDiscussionContent() == null || discussion.getDiscussionContent().isEmpty()) {
                result.put("success", false);
                result.put("message", "讨论内容不能为空");
                return result;
            }

            // 查询教师信息
            Teacher teacher = teacherService.findByTeacherNumber(teacherNumber);
            if (teacher == null) {
                result.put("success", false);
                result.put("message", "教师不存在");
                return result;
            }

            // 赋值教师属性
            discussion.setTeacherId(teacher.getTeacherID()); // 注意：实体类属性是teacherID（大写）
            discussion.setUserType("teacher");
            discussion.setUserName(teacher.getTeacherName());

            // ====================== 关键修改 ======================
            // 调用【教师专属插入方法】，而非通用插入方法（避免学生ID校验）
            int rows = discussionService.insertDiscussionByTeacher(discussion);
            // =====================================================

            if (rows > 0) {
                result.put("success", true);
                result.put("message", "讨论发布成功");
            } else {
                result.put("success", false);
                result.put("message", "讨论发布失败");
            }

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "讨论发布失败: " + e.getMessage());
        }
        return result;
    }

    @DeleteMapping("/teacher/delete/{discussionId}")
    public Map<String, Object> deleteTeacherDiscussion(
            @PathVariable Integer discussionId,
            @RequestParam("teacherNumber") String teacherNumber) {

        Map<String, Object> result = new HashMap<>();
        try {
            // 直接通过教师编号查询该教师发布的所有讨论
            List<Discussion> discussions = discussionService.findDiscussionsByTeacherNumber(teacherNumber);

            // 从结果中查找目标讨论ID
            Discussion targetDiscussion = discussions.stream()
                    .filter(d -> d.getDiscussionId().equals(discussionId))
                    .findFirst()
                    .orElse(null);

            if (targetDiscussion == null) {
                result.put("success", false);
                result.put("message", "讨论不存在或无权限删除");
                return result;
            }

            // 执行删除操作
            int rows = discussionService.deleteTeacherDiscussion(discussionId);
            if (rows > 0) {
                result.put("success", true);
                result.put("message", "讨论删除成功");
            } else {
                result.put("success", false);
                result.put("message", "讨论删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "讨论删除失败: " + e.getMessage());
        }
        return result;
    }
}

